package com.chushouya.controller.open;

import com.chushouya.common.constant.ServiceType;
import com.general.framework.core.schema.Response;
import com.chushouya.manager.dto.admin.oss.OssCallbackDTO;
import com.chushouya.manager.service.admin.AttachmentService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

/**
 * OSS 上传回调控制器
 * 
 * @author chushouya
 * @date 2025-08-13
 */
@Slf4j
@RestController
@RequestMapping(ServiceType.OPENAPI + "/oss")
@Api(tags = ServiceType.OPENAPI + "OSS回调接口")
public class OssCallbackController {

    @Autowired
    private AttachmentService attachmentService;

    /**
     * OSS 上传回调接口
     * 当文件上传到 OSS 完成后，OSS 会调用此接口通知上传结果
     */
    @PostMapping("/callback")
    @ApiOperation("OSS上传回调")
    public Response<String> callback(OssCallbackDTO callbackDTO) {
        try {
            log.info("收到OSS上传回调通知");
            log.info("回调参数: {}", callbackDTO);

            // 调用服务处理回调
            attachmentService.handleOssCallback(callbackDTO);

            // 返回成功响应给 OSS
            return Response.success("OK");

        } catch (Exception e) {
            log.error("处理OSS回调失败", e);
            // 即使处理失败，也要返回成功给OSS，避免OSS重复回调
            return Response.success("OK");
        }
    }

    /**
     * OSS 回调验证接口（可选）
     * 用于验证回调请求的合法性
     */
    @GetMapping("/callback")
    @ApiOperation("OSS回调验证")
    public Response<String> verifyCallback(HttpServletRequest request) {
        log.info("收到OSS回调验证请求");
        
        // 记录请求参数
        request.getParameterMap().forEach((key, values) -> {
            log.info("参数 {}: {}", key, String.join(",", values));
        });

        return Response.success("OK");
    }
}
